package com.vitaf.cash.app.ui.fragment

import android.Manifest
import android.app.Activity.RESULT_OK
import android.content.Intent
import android.graphics.Typeface
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComFmt
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.VitafFmtStepSelfieBinding
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.event.room.VitafPointManager
import com.vitaf.cash.app.utils.VitafImgLoader
import com.vitaf.cash.app.utils.helper.VitafPermissionHp
import com.vitaf.cash.app.utils.log.VitafLog
import com.vitaf.cash.app.ui.activity.VitafCameraSelfieAct
import com.vitaf.cash.app.ui.activity.VitafProcessStepsAct
import com.vitaf.cash.app.ui.dialog.VitafPermissionReasonDlog
import com.vitaf.cash.lib.adapter.VitafOnSingleClickListener
import org.json.JSONObject
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 13:40
 * @Annotation：认证流程 - 自拍照
 */
class VitafStepSelfieFmt(): VitafComFmt(),EasyPermissions.PermissionCallbacks,EasyPermissions.RationaleCallbacks {
    private var _binding: VitafFmtStepSelfieBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "gombe credit step selfie binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var stepItem: JSONObject? = null

    //本地预览地址
    private var faceImgPath = ""
    //拍摄的头像地址
    private var faceImgUrl = ""

    constructor(stepItem: JSONObject): this(){
        this.stepItem = stepItem
    }

    override fun createVitafContentView(inflater: LayoutInflater): View {
        _binding = VitafFmtStepSelfieBinding.inflate(inflater)
        return binding.root
    }

    override fun initializeVitafViews() {
        initSelfieDataSecurityTipsView()
        initSelfieUploadCreditLimitApprovedTipsText()
        showGombeCreditStepSelfieBeforeView()
    }

    override fun setupVitafEventListeners() {
        _binding?.selfieImageLayout?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                if (EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)){
                    openGombeCreditStepSelfieCamera()
                } else {
                    showGombeCreditSelfiePermissionReasonDialog()
                }
            }
        })
        //提交
        _binding?.buttonStartOrSubmit?.setOnClickListener(object : VitafOnSingleClickListener(){
            override fun onSingleClick(v: View?) {
                //开始人脸拍照
                if (faceImgUrl.isEmpty()){
                    _binding?.selfieImageLayout?.callOnClick()
                    return
                }
                //提交
                val params = JSONObject().addCommonParams().apply {
                    put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_OCR_INFO_PATH)
                    put("cardType","FACE")//证件类型（PASSPORT、IDCARD、DRIVING、FACE、NONE）
                    put("faceImgUrl",faceImgUrl)//人脸图片
                }
                VitafLog.e(">>>>>>>selfie>>>>>>params ：$params")
                addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_SELFIE_CONFIRM_SUBMIT)
                // TODO: 进件信息点下一步 需上报所有埋点
                VitafPointManager.getInstance().manualReport()

                submitGombeCreditSelfieDataAction(params)
            }
        })
    }

    override fun loadVitafData() {
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_SELFIE_START)
    }

    /**
     * 数据安全提示
     */
    private fun initSelfieDataSecurityTipsView(){
        val showKey = getString(R.string.gombe_credit_process_step_selfie_data_security_key)
        val showText = String.format(getString(R.string.gombe_credit_process_step_selfie_data_security),showKey)
        val startIndex = showText.indexOf(showKey)
        val spannable = SpannableString(showText)
        spannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FF000FCC)), startIndex, startIndex + showKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textSelfieTips?.text = spannable
    }

    private fun initSelfieUploadCreditLimitApprovedTipsText(){
        val showApprovedKey = getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_approved_tips_key1)
        val showApprovedText = String.format(getString(R.string.gombe_credit_process_step_ocr_upload_credit_limit_approved_tips),showApprovedKey)
        val startApprovedIndex = showApprovedText.indexOf(showApprovedKey)
        val approvedTipsSpannable = SpannableString(showApprovedText)
        approvedTipsSpannable.setSpan(ForegroundColorSpan(getColor(R.color.gombe_credit_FFFF5900)), startApprovedIndex, startApprovedIndex + showApprovedKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        //加粗
        approvedTipsSpannable.setSpan(StyleSpan(Typeface.BOLD), startApprovedIndex, startApprovedIndex + showApprovedKey.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        _binding?.textSelfieUploadCreditLimitApprovedTips?.text = approvedTipsSpannable
    }

    /**
     * 人脸拍照
     */
    private val selfieCameraResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            RESULT_OK -> {
                result.data?.let {
                    val faceImgPath = it.getStringExtra("imgLocalPath").toString()
                    VitafLog.e(">>>>>>>>>face info ：$faceImgPath")
                    val imgLocalPath = it.getStringExtra("imgLocalPath").toString()
                    val imgUrl = it.getStringExtra("imgUrl").toString()
                    showGombeCreditStepSelfieAfterView(imgLocalPath,imgUrl)
                }
            }
        }
    }

    /**
     * 显示未拍照View
     */
    private fun showGombeCreditStepSelfieBeforeView(){
        _binding?.selfieMaskView?.visibility = View.GONE
        _binding?.selfieRetakeLayout?.visibility = View.GONE
        _binding?.imgSelfie?.setImageResource(R.mipmap.gombe_credit_image_step_selfie_default_icon)
        _binding?.buttonStartOrSubmit?.text = getString(R.string.vitaf_btn_take_selfie)
    }

    /**
     * 显示拍照之后的View
     */
    private fun showGombeCreditStepSelfieAfterView(imgPath: String, imgUrl: String){
        faceImgPath = imgPath
        faceImgUrl = imgUrl
        _binding?.let { binding ->
            VitafImgLoader.instance?.loadImageUrl(requireContext(),binding.imgSelfie,faceImgPath)
            binding.selfieMaskView.visibility = View.VISIBLE
            binding.selfieRetakeLayout.visibility = View.VISIBLE
            binding.buttonStartOrSubmit.text = getString(R.string.vitaf_btn_confirm_submit)
            val eventRemark = "FACE Url $$$imgUrl"
            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_FORM.STEP_SELFIE_UPLOAD_URL,eventRemark)
        }
    }

    /**
     * 显示权限描述文案
     */
    private fun showGombeCreditSelfiePermissionReasonDialog(){
        val item = VitafPermissionHp.queryGombeCreditPermissionItem4()
        val requestPermission = item.optString("permission")
        val dialog = VitafPermissionReasonDlog(requireContext(),requestPermission,object : VitafPermissionReasonDlog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view?.id){
                    R.id.btnAgree -> {
                        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_AGREE,requestPermission)
                        EasyPermissions.requestPermissions(this@VitafStepSelfieFmt, getString(R.string.gombe_credit_process_step_selfie_camera_reason),1001,Manifest.permission.CAMERA)
                    }
                    R.id.btnDeny -> {
                        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_REASON_DIALOG_DENY,requestPermission)
                    }
                }
            }
        })
        dialog.setCancelable(true)
        dialog.setCanceledOnTouchOutside(true)
        dialog.show()
        dialog.showGombeCreditPermissionReasonData(item)
    }

    /**
     * 打开相机
     */
    private fun openGombeCreditStepSelfieCamera(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.STEP_SELFIE_START_TAKE)
        selfieCameraResultLauncher.launch(Intent(context, VitafCameraSelfieAct::class.java))
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        // 进一步使用 EasyPermissions 处理后续结果
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 用户点击同意授权后会回调该方法
     */
    override fun onPermissionsGranted(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_AGREE, it)
        }
        if (requestCode == 1001){
            openGombeCreditStepSelfieCamera()
        }
    }

    /**
     * 用户点击拒绝授权后会回调该方法
     */
    override fun onPermissionsDenied(requestCode: Int, perms: MutableList<String>) {
        perms.forEach {
            addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.PERMISSION_SYSTEM_DENY, it)
        }
        // 如果申请的权限中有任何一个权限存在 永久拒绝 的情况
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            // 设置 引导用户前往设置界面 自行设置权限的引导对话框
            AppSettingsDialog.Builder(this)
//                .setTitle("需要手动设置权限")
//                .setRationale("存在永久拒绝的权限 , 需要手动前往设置界面为应用进行授权")
//                .setPositiveButton("前往设置界面")
//                .setNegativeButton("不使用该功能")
                .build().show()
        }
    }

    override fun onRationaleAccepted(requestCode: Int) {
        VitafLog.e("onRationaleAccepted, code: $requestCode")
    }

    override fun onRationaleDenied(requestCode: Int) {
        VitafLog.e("onRationaleDenied, code: $requestCode")
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == 1001){
            // 判断五种权限是否申请成功
            val hasPermissions = EasyPermissions.hasPermissions(requireContext(), Manifest.permission.CAMERA)
            if (hasPermissions){
                openGombeCreditStepSelfieCamera()
            }
        }
    }

    /**
     * 提交
     */
    private fun submitGombeCreditSelfieDataAction(params: JSONObject){
        val act = getAct() as VitafProcessStepsAct
        act.onGombeCreditProcessStepSubmitAction(params)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_PAGE.STEP_SELFIE_END)
    }
}